package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.igas.bomp.facade.BompMchntManageService;
import cc.rengu.igas.bomp.facade.bean.SysParamBean;
import cc.rengu.igas.bomp.facade.request.ImageFileUpDownloadRequest;
import cc.rengu.igas.bomp.facade.request.ParamQueryRequest;
import cc.rengu.igas.bomp.facade.response.ImageFileUpDownloadResponse;
import cc.rengu.igas.bomp.facade.response.ParamQueryResponse;
import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.enums.ParamQueryKeyEnum;
import cc.rengu.redp.bizimpl.enums.QrcodeTypeEnum;
import cc.rengu.redp.bizimpl.igas.domain.SUserInfo;
import cc.rengu.redp.bizimpl.igas.service.SUserInfoService;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.QrcodeBatchInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpSysParam;
import cc.rengu.redp.bizimpl.upmp.service.IQrcodeBatchInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpBMchntBaseInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.*;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.QRcodeUtil;
import cc.rengu.redp.bizimpl.utils.ZXingCodeUtil;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.properties.RedpProperties;
import cc.rengu.redp.common.utils.SpringContextUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Api(tags = "商户管理:商户二维码管理")
@RestController
@RequestMapping(value = "/admin/merParam/qrcode")
public class QrcodeBatchInfoController extends BaseController {

    @Value("${download_file_dir}")
    private String filePathPrefix;

    private final static String baseFilePath = SpringContextUtil.getBean(RedpProperties.class).getBaseFilePath();


    @Autowired
    private IQrcodeBatchInfoService qrcodeInfoService;

    @Autowired
    private IUpmpBMchntBaseInfoService bMchntBaseInfoService;

//    @DubboReference(version = "2.2.0", url = "dubbo://172.17.100.9:62132", check = false)
    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntManageService bompMchntManageService;

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private SUserInfoService sUserInfoService;

        @DubboReference(version = "${dubbo.protocol.version}", check = false)
//    @DubboReference(version = "2.2.0", url = "dubbo://172.17.100.9:62132", check = false)
    private BompMchntManageService mchntManageService;

    //@RequiresPermissions("商户管理:商户二维码管理")
    @GetMapping(value = "")
    public Map<String, Object> index(Model model) throws RedpException {
        Map<String, Object> result = Maps.newHashMap();
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        result.put("isAdmin", user.isAdmin() ? 1 : 0);
        result.put("instId", user.getInstId());

        //查询系统参数，法人行二维码生成数量最大限制值
        ParamQueryRequest req = new ParamQueryRequest();
        req.setUserId(user.getId());
        req.setParamType(BusinessContainer.MCMP_TO_BOMP_PARAM_TYPE);
        req.setParamKey(ParamQueryKeyEnum.MAX_BATCH_APPLY_QR_NUM.getType());
        ParamQueryResponse paramResp = bMchntBaseInfoService.paramQuery(user.getInstId(), req, bMchntBaseInfoService.genMerOrder(user.getInstId()));
        if (Common.isNotBlank(paramResp)) {
            List<SysParamBean> sysParamList = paramResp.getSysParamList();
            if (CollectionUtils.isNotEmpty(sysParamList)) {
                result.put("qrCodeMaxNum", sysParamList.get(0).getParamValue());
            } else {
                result.put("qrCodeMaxNum", "3000");
            }
        } else {
            result.put("qrCodeMaxNum", "3000");
        }
        return result;
    }


    @RequiresPermissions("genqrcode:list")
    @GetMapping(value = "/list")
    public Map<String, Object> findByPage(QueryRequest request, QrcodeBatchInfo info) throws RedpException {
        return getDataTable(qrcodeInfoService.findByPageToMap(request, info));
    }

    @RequiresPermissions("genqrcode:list")
    @GetMapping(value = "/listDtl")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = false, dataType = "String"), @ApiImplicitParam(paramType = "query", name = "qrCodeBatchNo", value = "二维码批次号", required = false, dataType = "String"), @ApiImplicitParam(paramType = "query", name = "qrCodeType", value = "二维码类型", required = false, dataType = "String"), @ApiImplicitParam(paramType = "query", name = "qrStatus", value = "状态", required = false, dataType = "String")})
    public Map<String, Object> findDtlByPage(HttpServletRequest request, QueryRequest queryRequest) throws RedpException {
        return getDataTable(qrcodeInfoService.findDtlByPageToMap(request, queryRequest));
    }
    @RequiresPermissions("mchntqrcode:list")
    @GetMapping(value = "/listForMchnt")
    public Map<String, Object> findForMchntByPage(QueryRequest request, QrcodeForMchntReqVO qrcodeForMchntReqVO) throws RedpException {
        return getDataTable(qrcodeInfoService.findForMchntByPage(request, qrcodeForMchntReqVO));
    }

    @RequiresPermissions("mchntqrcode:list")
    @GetMapping(value = "/listForMchntDtl")
    public Map<String, Object> findDtlForMchntByPage(QueryRequest queryRequest, QrcodeForMchntDtlReqVO qrcodeForMchntDtlReqVO) throws RedpException {
        IPage<QrcodeForMchntDtlRespVO> result =qrcodeInfoService.findDtlForMchntByPage( queryRequest,qrcodeForMchntDtlReqVO);
        result.getRecords().stream().forEach(r -> {
            SUserInfo userInfo = sUserInfoService.findByUK(r.getInstId(),r.getUserId());
            r.setUserName(userInfo.getUserName());
            }
        );
        return getDataTable(result);
    }

    @GetMapping(value = "/logoPathSelect2List")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "q", value = "参数", required = false, dataType = "String")})
    public Map<String, Object> logoPathSelect2List(HttpServletRequest request) {
        String q = request.getParameter("q");
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");

        String instId = "";
        String[] param = q.split("&");
        if (null != param && param.length > 0) {
            instId = param[0];
        }
        List<Object> list = new ArrayList<>();
        Map<String, String> idNameMap;
        Map<String, String> map = upmpSysParamService.findMapDataByPrimaryKey(BusinessContainer.LOGO_URL_PATH_PARAM, instId, null);
        for (String key : map.keySet()) {
            idNameMap = new HashMap<>();
            idNameMap.put("id", key);
            idNameMap.put("name", map.get(key));
            list.add(idNameMap);
        }
        Map<String, Object> maps = new HashMap<>();
        maps.put("results", list);
        maps.put("more", false);
        return maps;
    }

    @GetMapping(value = "/qrcodeTemplateSelect2List")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "q", value = "参数", required = false, dataType = "String")})
    public Map<String, Object> qrcodeTemplateSelect2List(HttpServletRequest request) {
        String q = request.getParameter("q");
        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");
        String instId = "";
        String[] param = q.split("&");
        if (null != param && param.length > 0) {
            instId = param[0];
        }
        List<Object> list = new ArrayList<>();
        Map<String, String> idNameMap;
        Map<String, String> map = upmpSysParamService.findMapDataByPrimaryKey(BusinessContainer.QRCODE_TEMPLATE_PARAM, instId, null);
        for (String key : map.keySet()) {
            idNameMap = new HashMap<>();
            idNameMap.put("id", key);
            idNameMap.put("name", map.get(key));
            list.add(idNameMap);
        }
        Map<String, Object> maps = new HashMap<>();
        maps.put("results", list);
        maps.put("more", false);
        return maps;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public void singleFileUpload(HttpServletRequest request, @RequestParam("imgFile") CommonsMultipartFile fileUpload, HttpServletResponse response) throws RedpException {
        Map<String, Object> retMap = Maps.newHashMap();
        try {
            if (fileUpload != null && !fileUpload.isEmpty()) {
                log.info("single file upload ====== file.size = " + fileUpload.getSize());
                String name = fileUpload.getOriginalFilename();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                String suffix = "";
                if (StringUtils.isNotBlank(name)) {
                    suffix = name.substring(name.lastIndexOf(".") + 1);
                    if ("jpg".equals(suffix) || "JPG".equals(suffix) || "gif".equals(suffix) || "GIF".equals(suffix) || "png".equals(suffix) || "PNG".equals(suffix) || "bmp".equals(suffix) || "BMP".equals(suffix)) {
                    } else {
                        throw new RuntimeException("上传文件请选择格式为 .jpg .JPG .gif .GIF .png .PNG .bmp .BMP的附件上传！");
                    }
                }
                //获取当前时间并作为时间戳
                String timeStamp = simpleDateFormat.format(new Date());
                name = timeStamp + "." + suffix;
// 获取图片存储地址
//                 String path = ServletUtils.writeUploadFile(fileUpload.getInputStream(), name, fileUpload.getSize());
                String path = filePathPrefix;
                if (StringUtils.isNotBlank(path)) {
                    String type = request.getParameter("type");
                    UpmpSysParam parent;
                    String dataType;
                    String dataName;
                    String instId = upmpSysParamService.getById(UpmpConstant.IGAS_DEFAULT_INST_ID).getPrimaryValue();
                    if (StringUtils.isNotBlank(type) && type.equals("qrcodeTemplate")) {
                        // 二维码模板
                        parent = upmpSysParamService.findByPrimaryKey(BusinessContainer.QRCODE_TEMPLATE_PARAM, instId, null);
                        dataType = BusinessContainer.QRCODE_TEMPLATE_PARAM;
                        dataName = "商户二维码模板图片";
                    } else {
                        // 中心logo图片
                        parent = upmpSysParamService.findByPrimaryKey(BusinessContainer.LOGO_URL_PATH_PARAM, instId, null);
                        dataType = BusinessContainer.LOGO_URL_PATH_PARAM;
                        dataName = "商户二维码中心logo图片";
                    }
                    UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                    if (null == parent) {
                        // 创建二维码模板参数
                        parent = new UpmpSysParam();
                        parent.setInstId(user.getInstId());
                        parent.setPrimaryKey(dataType);
                        parent.setPrimaryValue(dataName);
                        upmpSysParamService.save(parent);
                    }
                    // 将上传的图片维护到参数表中
                    UpmpSysParam dataDict = new UpmpSysParam();
                    dataDict.setInstId(user.getInstId());
                    dataDict.setPrimaryKey(path);
                    dataDict.setPrimaryValue(name);
                    dataDict.setParentId(parent.getParentId());
                    upmpSysParamService.save(dataDict);
                    // 应答
                    retMap.put("error", 0);
                    retMap.put("url", path);
                    retMap.put("path", path);
                    response.setContentType(MediaType.TEXT_PLAIN_VALUE + "; charset=UTF-8");
                    response.getWriter().print(retMap);
                }
            }
        } catch (IOException e) {
            throw new RedpException("Upload file error" + e.getMessage());
        }

    }

    //@RequiresPermissions("商户管理:商户二维码管理")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)

    public OperationResult editSave(@ModelAttribute("qrcodeInfo") QrcodeBatchInfo entity, Model model) {
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
//    	getEntityService().save(entity);
//    	result.put("id", entity.getId());
        //TODO 添加实际业务操作
        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }

    @ApiOperation(value = "批量申请二维码")
    @RequiresPermissions("genqrcode:batchapply")
    @RequestMapping(value = "/batchQrcode", method = RequestMethod.POST)
    public OperationResult batchQrcode(@RequestParam("qrCodeNum") String qrCodeNum, @RequestParam("qrCodeType") String qrCodeType, @RequestParam("instId") String instId) throws RedpException {
        if (QrcodeTypeEnum.CUPS_CODE.getType().equals(qrCodeType)) {
            log.info("接收到界面发起批量生成银联二维码请求，数量[{}]", qrCodeNum);
            return qrcodeInfoService.batchQrcode(qrCodeNum);
        } else if (QrcodeTypeEnum.IGAS_CODE.getType().equals(qrCodeType)) {
            log.info("接收到界面发起批量生成聚合码请求，数量[{}]", qrCodeNum);
            return qrcodeInfoService.generateMchntQrCode(qrCodeNum, instId);
        } else {
            return OperationResult.buildFailureResult("不支持该种类型的二维码");
        }
    }

    @ApiOperation(value = "二维码状态管理")
    @RequiresPermissions(value = {"genqrcode:stop","genqrcode:use","genqrcode:cancel","mchntqrcode:stop","mchntqrcode:use","mchntqrcode:cancel"},logical = Logical.OR)
    @RequestMapping(value = "/qrcodeManager", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "instId", value = "机构标识", required = true, dataType = "String"), @ApiImplicitParam(paramType = "query", name = "qrCode", value = "二维码编号", required = true, dataType = "String"), @ApiImplicitParam(paramType = "query", name = "qrCodeType", value = "二维码类型", required = true, dataType = "String"), @ApiImplicitParam(paramType = "query", name = "optFlag", value = "操作标识", required = true, dataType = "String")})
    public OperationResult qrcodeManager(HttpServletRequest request) throws RedpException {
        String oprType = "";
        String qrcodeStatus = "";
        String instId = request.getParameter("instId");
        String qrCodeType = request.getParameter("qrCodeType");
        String qrCode = request.getParameter("qrCode");
        String qrNum = request.getParameter("qrNum");
        String mchntNo = request.getParameter("mchntNo");
        String qrMchntNo = request.getParameter("qrMchntNo");
        String optFlag = request.getParameter("optFlag");

        if ("stop".equals(optFlag)) {
            oprType = BusinessContainer.UPQRCODE_OPRTYPE_01;
            qrcodeStatus = "01";
        } else if ("use".equals(optFlag)) {
            oprType = BusinessContainer.UPQRCODE_OPRTYPE_02;
            qrcodeStatus = "00";
        } /*else if ("cancel".equals(optFlag)) {
            oprType = BusinessContainer.UPQRCODE_OPRTYPE_03;
            qrcodeStatus = "01";
        }*/
        //    if (QrcodeTypeEnum.IGAS_CODE.getType().equals(qrCodeType)) {
        qrcodeInfoService.qrcodeStatusUpd(qrcodeStatus, instId, qrCodeType, qrCode);
       /* } else if (QrcodeTypeEnum.CUPS_CODE.getType().equals(qrCodeType)) {

            MerBaseInfoR merbase = merBaseInfoRService.getMerByMerCd(mchntNo);
            // TODO：查询机构信息需用新版表结构字段，目前先用用户信息。待修改；
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            UpmpOrganization org = organizationService.getOrgByCode(merbase.getManageOrg(), user.getInstId());
            MerUpqrR merUpqrR = merUpqrRService.find(mchntNo);
            qrcodeInfoService.qrcodeManager(merBaseInfoService, merUpqrR, merbase, oprType, org, qrCodeType);
        } else {

            return OperationResult.buildFailureResult("异常数据，请联系管理员！");
        }*/
        return OperationResult.buildSuccessResult("数据操作处理完成");
    }


    //@RequiresPermissions("商户管理:商户二维码管理")
    @RequiresPermissions("genqrcode:export")
    @GetMapping(value = "/exportBatch")
    public Map<String, Object> exportBatchShow(HttpServletRequest request, Model model) throws RedpException {
        Map<String, Object> result = Maps.newHashMap();
        result.put("optFlag", "exportBatch");
        result.put("applyBatchNo", request.getParameter("applyBatchNo"));
        result.put("instId", request.getParameter("instId"));
        result.put("qrCodeType", request.getParameter("qrCodeType"));
        result.put("qrStatus", request.getParameter("qrStatus"));
        try {
            result.put("qrUrl", URLEncoder.encode("页面所生成二维码为模拟数据，具体以导出文件为准", "UTF-8"));
            result.put("QRcode", URLEncoder.encode("页面所生成二维码为模拟数据，具体以导出文件为准", "UTF-8"));
        } catch (Exception e) {
            log.error("二维码导出异常", e);
            throw new RedpException("二维码导出异常");
        }
        return result;
//        return "admin/mer/merBaseInfo/merBaseInfo-QRcode";
    }

    //@RequiresPermissions("商户管理:商户二维码管理")
    @RequiresPermissions("genqrcode:export")
    @GetMapping(value = "/exportBatchs")
    public OperationResult exportBatch(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException, RedpException {
        List<Map> qrcodeInfoList = new ArrayList<>();
        String exportUrl = request.getParameter("exportUrl");
        String dateTime = request.getParameter("dateTime");
        if ("true".equals(exportUrl) || "false".equals(exportUrl)) {
            qrcodeInfoList = qrcodeInfoService.findDtlToList(request);
            if (qrcodeInfoList == null || qrcodeInfoList.isEmpty()) {
                return OperationResult.buildFailureResult("没有检索到要处理的数据");
            }
            log.info("要导出的二维码记录数:[{}]", qrcodeInfoList.size());
            dateTime = CommonUtils.getCurrentDate("yyyyMMddHHmmssSSS");
        }
        Iterator<Map> it = qrcodeInfoList.iterator();

       /* if (Common.isBlank(filePathPrefix)) {
            filePathPrefix = request.getSession().getServletContext().getRealPath(File.separator);
        }
        // 去掉路径最后的“/”
        if (filePathPrefix.endsWith(File.separator)) {
            filePathPrefix = filePathPrefix.substring(0, filePathPrefix.length() - 1);
        }*/
        String instId = request.getParameter("instId");
        String path = filePathPrefix + File.separator + "download" + File.separator + dateTime + File.separator;
//        String path = "/epaydata/mcmp/QrcodeFile/" + instId + File.separator + dateTime + File.separator;
        //   String path = "C:\\Users\\800P_moxm\\Desktop\\qrFile\\"+ instId + File.separator + dateTime + File.separator;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String templatePath = request.getParameter("templatePath");

        if (StringUtils.isNotBlank(exportUrl) && exportUrl.equals("false")) {
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String tempImageData = "";
            if (StringUtils.isNotBlank(templatePath)) {
                ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
                req.setImageType("04");
                req.setOprType("01");
                req.setUserId(user.getId());
                req.setImagePath(templatePath);
                OperationResult operationResult = bMchntBaseInfoService.imageFileUpDownload(user.getInstId(), req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), null);
                if (operationResult.getType().equals(OperationResult.OPERATION_RESULT_TYPE.success.name())) {
                    ImageFileUpDownloadResponse resp = (ImageFileUpDownloadResponse) operationResult.getData();
                    tempImageData = resp.getImageData();
                }
            }
            qrcodeInfoService.batchQrcodeImage(it, path, request, templatePath, tempImageData, user);
            java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
            return OperationResult.buildSuccessResult(dateTime, result);
        } else if ("true".equals(exportUrl)) {
            // 纯URL写入文件
            File file = new File(path + "二维码URL.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fileWriter);
            while (it.hasNext()) {
                Map map = it.next();
                String content = map.get("qrUrl").toString();
                try {
                    bw.write(content + "\r\n");
                } catch (Exception e) {
                    log.error("写文件异常", e);
                    throw new RedpException("写文件异常");
                }
            }
            bw.close();
        }

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        File zipFile = new File(path + File.separator + dateTime + ".zip");
        try {
            if (zipFile.exists()) {
                log.error(path + "目录下存在名字为:" + dateTime + ".zip" + "打包文件.");
            } else {
                File sourceFile = new File(path);
                File[] sourceFiles = sourceFile.listFiles();
                if (null == sourceFiles || sourceFiles.length < 1) {
                    log.error("待压缩的文件目录：" + path + "里面不存在文件，无需压缩.");
                } else {
                    fos = new FileOutputStream(zipFile);
                    zos = new ZipOutputStream(new BufferedOutputStream(fos));
                    byte[] bufs = new byte[1024 * 10];
                    for (int i = 0; i < sourceFiles.length; i++) {
                        //创建ZIP实体，并添加进压缩包
                        ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                        zos.putNextEntry(zipEntry);
                        //读取待压缩的文件并写进压缩包里
                        fis = new FileInputStream(sourceFiles[i]);
                        bis = new BufferedInputStream(fis, 1024 * 10);
                        int read = 0;
                        while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                            zos.write(bufs, 0, read);
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            log.error("压缩文件出现异常", e);
            throw new RedpException("压缩文件出现异常" + e.getCause());
        } catch (IOException e) {
            log.error("压缩文件出现异常", e);
            throw new RedpException("压缩文件出现异常" + e.getCause());
        } finally {
            //关闭流
            try {
                if (null != bis) bis.close();
                if (null != zos) zos.close();
            } catch (IOException e) {
                log.error(e.getMessage());
                throw new RuntimeException(e);
            }
        }

        BufferedInputStream biStr = null;
        BufferedOutputStream bos = null;
        try {
            String contentType = "application/octet-stream";
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");

            long fileLength = zipFile.length();

            response.setContentType(contentType);
            response.setHeader("Content-disposition", "attachment; filename=" + new String(dateTime.getBytes("utf-8"), "ISO8859-1") + ".zip");
            response.setHeader("Content-Length", String.valueOf(fileLength));
            biStr = new BufferedInputStream(new FileInputStream(zipFile));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = biStr.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bos.flush();
        } catch (Exception e) {
            log.error("文件下载出现异常", e);
            throw new RedpException("文件下载出现异常" + e.getCause());
        } finally {
            if (null != biStr) {
                try {
                    biStr.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    log.error("关闭输入流biStr出现异常：{}", e.getMessage(), e);
                }

            }
            if (null != bos) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    log.error("关闭输出流bos出现异常：{}", e.getMessage(), e);
                }
            }
            File parentDir = new File(filePathPrefix + File.separator + "download" + File.separator);
//            File parentDir = new File("/epaydata/mcmp/QrcodeFile/" + instId + File.separator);
            //     File parentDir = new File("C:\\Users\\800P_moxm\\Desktop\\qrFile\\"+ instId + File.separator);
            FileUtils.deleteDirectory(parentDir);
        }

        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        return OperationResult.buildSuccessResult("操作处理完成", result);
    }

    @PostMapping("/isExport")
    @ResponseBody
    public OperationResult isExport(HttpServletRequest request) {
        String exportFlag = request.getParameter("exportKey");
        String result = request.getSession().getAttribute(exportFlag) == null ? "" :
                (String) request.getSession().getAttribute(exportFlag);
        return OperationResult.buildSuccessResult("success", result);
    }

    @ApiOperation(value = "银联批量二维码查询")
    //@RequiresPermissions("商户管理:商户二维码管理")
    @RequestMapping(value = "/batchQrcodeQuery", method = RequestMethod.POST)

    public OperationResult batchQrcodeQuery(@RequestParam("qrCodeType") String qrCodeType, @RequestParam("applyBatchNo") String applyBatchNo, @RequestParam("totlaNum") String totlaNum) throws RedpException {

        if (QrcodeTypeEnum.CUPS_CODE.getType().equals(qrCodeType)) {
            return qrcodeInfoService.cupsBatchQrcodeQuery(applyBatchNo, totlaNum);
        } else {
            return OperationResult.buildFailureResult("异常数据，请联系管理员！");
        }
    }

    @RequestMapping(value = "/setUrl", method = RequestMethod.POST)
    public OperationResult setLogoUrl(HttpServletRequest request) throws RedpException {
        String instId = request.getParameter("instId");
        String qRcode = request.getParameter("qRcode");
        String applyBatchNo = request.getParameter("applyBatchNo");
        String imageLocalPath = request.getParameter("imageLocalPath");
        java.util.Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        qrcodeInfoService.updateQrcodeLogoUrl(instId, qRcode, applyBatchNo, imageLocalPath);
        return OperationResult.buildSuccessResult(result);
    }

    // 二维码查看
//    @RequiresPermissions("商户管理:商户信息维护")
    @RequiresPermissions(value = {"genqrcode:view","mchntqrcode:view"},logical = Logical.OR)
    @GetMapping(value = "/QRcode")
    public Map<String, Object> QRcode(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = Maps.newHashMap();
        String instId = request.getParameter("instId");// 银行代码
        String qrCode = (request.getParameter("qrCode") == null || "".equals(request.getParameter("qrCode"))) ? "0" : request.getParameter("qrCode");
        String qrUrl = (request.getParameter("qrUrl") == null || "".equals(request.getParameter("qrUrl"))) ? "0" : request.getParameter("qrUrl");
        String logoUrlPath = request.getParameter("logoUrlPath") == null ? "" : request.getParameter("logoUrlPath");
        String qrCodeType = request.getParameter("qrCodeType");// 二维码类型
//		Map rst = qrcodeInfoService.getQrcodeInfoByUk(instId, qrCode, qrCodeType);
//		String qrcode = rst.get("qrCode");
        result.put("QRcode", qrCode);

        try {
            String qrUrlEncode = URLEncoder.encode(qrUrl, "UTF-8");
            result.put("qrUrl", qrUrlEncode);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }
        LinkedHashMap<String, String> codeStyle = new LinkedHashMap<String, String>();
        codeStyle.put("00", "简洁版");
        codeStyle.put("01", "整合版");

        LinkedHashMap<String, String> resolution = new LinkedHashMap<String, String>();
        resolution.put("00", "普通");
        resolution.put("01", "高清");

        Map<String, String> allPayMethods = upmpSysParamService.findMapDataByPrimaryKey(BusinessContainer.QRCODE_PAYMETHOD_PRIMARYKEY, instId, null);
        result.put("instId", instId);
        result.put("logoUrlPath", logoUrlPath);
        result.put("codeStyle", codeStyle);
        result.put("resolution", resolution);
        result.put("allPayMethods", allPayMethods);
        result.put("optFlag", "view");

        return result;
    }

    // 生成二维码图案
    @GetMapping(value = "/getQRcode")
    public String getQRcode(HttpServletRequest request, HttpServletResponse response) throws IOException, RedpException {
        BufferedImage bufferedImage;
        String QRSuffix = request.getParameter("QRSuffix");
        if (StringUtils.isNotEmpty(QRSuffix)) {
            QRSuffix = QRSuffix.replaceAll("&amp;", "&");
        }
        String logoPath = request.getParameter("logoPath");
        //调联机接口上传logo的路径
        String logoUrlPath = request.getParameter("logoUrlPath");
        if (StringUtils.isNotBlank(logoPath)) {
            logoPath = URLDecoder.decode(logoPath, "UTF-8");
            String backgroundImgPath = filePathPrefix + logoPath;
            bufferedImage = QRcodeUtil.enCode(QRSuffix, new File(backgroundImgPath));
        } else if (StringUtils.isNotBlank(logoUrlPath)) {
            String qrCode = StringUtils.isNotBlank(request.getParameter("qrCode")) ? request.getParameter("qrCode") : "0";
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
            req.setImageType("03");
            req.setOprType("01");
            req.setUserId(user.getId());
            req.setImageLocalPath(logoUrlPath);
            OperationResult operationResult = bMchntBaseInfoService.imageFileUpDownload(user.getInstId(), req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), null);
            if (operationResult.getType().equals(OperationResult.OPERATION_RESULT_TYPE.success.name())) {
                ImageFileUpDownloadResponse resp = (ImageFileUpDownloadResponse) operationResult.getData();
                logoUrlPath = new String(Base64.getDecoder().decode(logoUrlPath));
                String fileSuffix = logoUrlPath.substring(logoUrlPath.lastIndexOf("."));
                String fileName = qrCode + fileSuffix;

                byte[] fileBytes = Base64.getDecoder().decode(resp.getImageData());
                String path = baseFilePath + File.separator + fileName;
                File file = new File(path);
                if (!file.exists()) {
                    file.createNewFile();
                }
                OutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(file);
                    outputStream.write(fileBytes);
                    outputStream.flush();
                    bufferedImage = QRcodeUtil.enCode(QRSuffix, file);
                } catch (Exception e) {
                    log.error("图片生成异常", e);
                    throw new RedpException("图片生成异常");
                } finally {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                    if (null != file && file.exists()) {
                        file.delete();
                    }
                }
            } else {
                bufferedImage = QRcodeUtil.enCode(400, 400, QRSuffix);
            }
        } else {
            bufferedImage = QRcodeUtil.enCode(400, 400, QRSuffix);
        }
        // 图片处理
        if (bufferedImage != null) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", outputStream);
            byte[] bytes = outputStream.toByteArray();
            // 转BASE64编码字符串
            BASE64Encoder encoder = new BASE64Encoder();
            String base64String = encoder.encodeBuffer(bytes).trim();
            base64String = base64String.replaceAll("\n", "").replaceAll("\r", "");
            return "data:image/" + "png" + ";base64," + base64String;
        }
        return null;
    }
    // 根据传入的二维码模板，进行渲染二维码

    @GetMapping(value = "/getQRcodeByFile")
    public String getQRcodeByFile(HttpServletRequest request, HttpServletResponse response) throws IOException, RedpException {
        BufferedImage bufferedImage = null;
        String QRSuffix = request.getParameter("QRSuffix");
        if (StringUtils.isNotEmpty(QRSuffix)) {
            QRSuffix = java.net.URLDecoder.decode(java.net.URLDecoder.decode(QRSuffix, "UTF-8"), "UTF-8");
            QRSuffix = QRSuffix.replaceAll("&amp;", "&");
        }
        String logoPath = request.getParameter("logoPath");
        String backgroundImgPath = request.getParameter("templatePath");
        if (StringUtils.isBlank(backgroundImgPath)) {
            return null;
        }
        File tmpFile = null;
        File logFile = null;
        if (StringUtils.isNotBlank(backgroundImgPath)) {
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
            req.setImageType("04");
            req.setOprType("01");
            req.setUserId(user.getId());
            req.setImageLocalPath(backgroundImgPath);
            OperationResult operationResult = bMchntBaseInfoService.imageFileUpDownload(user.getInstId(), req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), null);
            if (operationResult.getType().equals(OperationResult.OPERATION_RESULT_TYPE.success.name())) {
                ImageFileUpDownloadResponse resp = (ImageFileUpDownloadResponse) operationResult.getData();
                backgroundImgPath = new String(Base64.getDecoder().decode(backgroundImgPath));
                String fileSuffix = backgroundImgPath.substring(backgroundImgPath.lastIndexOf("."));
                String fileName = "tmpFile" + fileSuffix;

                byte[] fileBytes = Base64.getDecoder().decode(resp.getImageData());
                String path = baseFilePath + File.separator + fileName;
                tmpFile = new File(path);
                if (!tmpFile.exists()) {
                    tmpFile.createNewFile();
                }
                OutputStream outputStream = new FileOutputStream(tmpFile);
                try {
                    outputStream.write(fileBytes);
                    outputStream.flush();
                } catch (Exception e) {
                    log.error("交易出现异常，异常信息：" + e.getMessage());
                } finally {
                    outputStream.close();
                }
            }
        }
        if (StringUtils.isNotBlank(logoPath)) {
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            ImageFileUpDownloadRequest req = new ImageFileUpDownloadRequest();
            req.setImageType("03");
            req.setOprType("01");
            req.setUserId(user.getId());
            req.setImageLocalPath(logoPath);
            OperationResult operationResult = bMchntBaseInfoService.imageFileUpDownload(user.getInstId(), req, bompMchntManageService, bMchntBaseInfoService.genMerOrder(user.getInstId()), null);
            if (operationResult.getType().equals(OperationResult.OPERATION_RESULT_TYPE.success.name())) {
                ImageFileUpDownloadResponse resp = (ImageFileUpDownloadResponse) operationResult.getData();
                logoPath = new String(Base64.getDecoder().decode(logoPath));
                String fileSuffix = logoPath.substring(logoPath.lastIndexOf("."));
                String fileName = "logFile" + fileSuffix;

                byte[] fileBytes = Base64.getDecoder().decode(resp.getImageData());
                String path = baseFilePath + File.separator + fileName;
                logFile = new File(path);
                if (!logFile.exists()) {
                    logFile.createNewFile();
                }
                OutputStream outputStream = new FileOutputStream(logFile);
                try {
                    outputStream.write(fileBytes);
                    outputStream.flush();
                } catch (Exception e) {
                    log.error("交易出现异常，异常信息：" + e.getMessage());
                } finally {
                    outputStream.close();
                }
            }
        }
        try {
            ZXingCodeUtil zp = new ZXingCodeUtil();
            BufferedImage bim = zp.getQR_CODEBufferedImage(QRSuffix, BarcodeFormat.QR_CODE, 400, 400, zp.getDecodeHintType());
            bufferedImage = zp.addLogoText_QRCode(bim, logFile, "", tmpFile);
        } catch (Exception e) {
            log.error("生成二维码失败", e);
        } finally {
            if (null != tmpFile && tmpFile.exists()) {
                tmpFile.delete();
            }
            if (null != logFile && logFile.exists()) {
                logFile.delete();
            }
        }

        // 图片处理
        if (bufferedImage != null) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", outputStream);
            byte[] bytes = outputStream.toByteArray();
            // 转BASE64编码字符串
            BASE64Encoder encoder = new BASE64Encoder();
            String base64String = encoder.encodeBuffer(bytes).trim();
            base64String = base64String.replaceAll("\n", "").replaceAll("\r", "");
            return "data:image/" + "png" + ";base64," + base64String;
        }
        return null;
    }

}
